package com.zklh.leetcode.tree.middle;

import com.zklh.leetcode.tree.model.TreeNode;

/**
 * 将二叉搜索树转为累加树
 * 思路, 定义一个全局的右边和, 然后按照先右 自己, 中间这个顺序维护当前节点的值, 以及rightSum的值
 * @author 坐看落花
 * @version 1.0
 * @date 2021/5/5 11:20
 */
public class GreaterSumTreeConverter {

    private int rightSum = 0;

    public TreeNode convertBST(TreeNode root) {
        traverse(root);
        return root;
    }

    public void traverse(TreeNode root) {

        if (root == null) {
            return;
        }

        traverse(root.right);

        root.val += rightSum;
        rightSum = root.val;

        traverse(root.left);

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(1);
        root.right = new TreeNode(6);
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(2);
        root.left.right.right = new TreeNode(3);
        root.right.left = new TreeNode(5);
        root.right.right = new TreeNode(7);
        root.right.right.right = new TreeNode(8);
        GreaterSumTreeConverter converter = new GreaterSumTreeConverter();
        converter.convertBST(root);
        System.out.println(converter.rightSum);
    }

}
